package com.tudouji.project.flow.service.impl;

import com.flow.service.advice.service.ICCAdviceService;
import com.flow.service.advice.service.impl.PendingAdviceServiceImpl;
import com.flow.service.config.FlowConfig;
import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.flow.FlowTemp;
import com.flow.service.pojo.result.AdviceResult;
import com.flow.service.pojo.user.FlowUser;
import com.flow.service.utils.ParserUtil;
import com.tudouji.common.utils.PotatojPostUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * @author xiaxl
 * @version v1.0
 * @ClassName CCAdviceServiceImpl
 * @Descrption
 * @date 2022/4/11 14:05
 */
@Service("ccAdviceService")
public class CCAdviceServiceImpl implements ICCAdviceService {

    @Autowired
    private PotatojPostUtils postUtils;

    @Override
    public AdviceResult sendCCAdvice(FlowUser user, BasePojo base, FlowTemp temp, FlowUser applyUser, String message) {
        AdviceResult result=new AdviceResult();
        Map<String,String> params=new HashMap<>();
        params.put("toUser",user.getNickName());
        params.put("code",base.getCode());
        params.put("openid",user.getOpenid());
        params.put("status",base.getStatus().toString());
        params.put("tempName",temp.getName());
        params.put("applyUser",applyUser.getNickName());
        params.put("msg",message);

        Map<String, Object> param = new Hashtable();
        param.put("visitPath", FlowConfig.getVisitPath());
        param.put("webPath", FlowConfig.getWebPath());
        String backUrl = ParserUtil.replaceWithMap(temp.getDetailUrl(), param);

        if(StringUtils.isNotBlank(backUrl)){
            if (backUrl.contains("?")) {
                if (StringUtils.isNotBlank(user.getOpenid()) && user.getOpenid().length() > 20) {
                    backUrl = backUrl + "&openid=" + user.getOpenid() + "&status=" + base.getStatus() + "&code=" + base.getCode();
                } else {
                    backUrl = backUrl + "&status=" + base.getStatus() + "&code=" + base.getCode();
                }

            } else {
                if (StringUtils.isNotBlank(user.getOpenid()) && user.getOpenid().length() > 20) {
                    backUrl = backUrl + "?openid=" + user.getOpenid() + "&status=" + base.getStatus() + "&code=" + base.getCode();
                } else {
                    backUrl = backUrl + "&status=" + base.getStatus() + "&code=" + base.getCode();
                }
            }
        }
        backUrl = backUrl.replace('#', '*');
        params.put("url",backUrl);

        Map<String, String> post = postUtils.post(params, "/weixin/WxTemplMsg!sendWxMsg.action?");
        result.setUrl(post.get("url"));
        result.setResult(post.get("result"));
        return result;
    }
}
